package com.yzt.zhuju.webview;

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.text.TextUtils;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.network.HttpUrlManager;
import com.yzt.p_base.utils.LogDataUtils;
import com.yzt.p_base.utils.NetworkUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author : bob
 * date   : 2022/12/9
 * desc   :
 */
public class AppWebViewClient extends WebViewClient {

    public static final String STARE_AROUT = "xysanchor://route:8080";  //路由的跳转

    public static final String START_CUSTOME = "xysanchor://custome:8080?event="; //自定义事件

    public static final String TYPE_BACK = "xys_back";           //返回

    public static final String TYPE_CLOSE = "xys_force_back";    //退出webview

    public static final String TYPE_FEADBACK = "feadback";  //跳转意见反馈

    public static final String TYPE_TEL = "tel"; //拨打电话

    public static final String TYPE_OUT_APP = "out_app";//调用外部app

    public static final String TYPE_BROWSER = "browser";  //浏览器打开

    //个人资料设置页
    public static final String TYPE_USERINFO_EDIT = "user_info_edit";
    //附近的人列表页/首页
    public static final String TYPE_HOME_PAGE = "home_page";
    // 账号密码设置
    public static final String TYPE_SET_PASSWORD = "set_password";

    // 跳转任意activity
    public static final String TYPE_OPEN_PAGE = "open_page";

    private String mUrl;

    private final WebViewListener mListener;

    private final BaseActivity baseActivity;

    public AppWebViewClient(BaseActivity activity, WebViewListener listener) {
        mListener = listener;
        baseActivity = activity;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        LogDataUtils.d("TEST", "WebViewUrl == " + url);
        mUrl = url;
        if (TextUtils.isEmpty(url)) {
            return true;
        }
        if (matcherStart(view)) {
            return true;
        }

        if (NetworkUtils.isWifiProxy()) {
            url = NetworkUtils.NETWORK_PROXY_PAGE;
        }

        if (baseActivity != null) {
            String hostStr = HttpUrlManager.getAppHttpUrl();
            baseActivity.setFullScreen(mUrl.startsWith(hostStr));
        }

        return super.shouldOverrideUrlLoading(view, url);
    }

    public interface WebViewListener {
        /**
         * 关闭页面
         */
        void finish();

        /**
         * 根据类型跳转
         */
        void turnOtherPage(String turnType, Map<String, String> params);

        /**
         * 根据路由跳转
         */
        void turnByARouter(String url);

        /**
         * 打开浏览器
         */
        void turnOpenBrowser(String url);

        /**
         * 资源加载完成
         */
        void onPageFinished(WebView view, String url);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //关闭加载动画
        if (mActivity != null) {
            ((BaseActivity) mActivity).closeProgress();
        }

        if (mListener != null) {
            mListener.onPageFinished(view, url);
        }
    }

    private Activity mActivity;

    public void setActivity(Activity mActivity) {
        this.mActivity = mActivity;
    }

    @Override
    public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
        super.onReceivedSslError(webView, sslErrorHandler, sslError);
    }

    /**
     * 匹配链接头部
     */
    private boolean matcherStart(WebView view) {

      if (mUrl.startsWith(STARE_AROUT)) {
            if (mListener != null) {
                mListener.turnByARouter(mUrl);
            }
            return true;
        } else if (mUrl.startsWith(START_CUSTOME)) {
            return matcherType(view);
        }
        return false;
    }

    private boolean matcherType(WebView view) {
        Matcher matcher = Pattern.compile("xysanchor:\\/\\/custome:8080\\?event=*").matcher(mUrl);
        if (!matcher.find()) {
            return false;
        }
        Map<String, String> params = getParamsMap(mUrl);

        switch (params.get("event")) {
            case TYPE_BACK:
                boolean canGoBack = view.canGoBack();
                if (canGoBack) {
                    view.goBack();
                    return false;
                } else {
                    if (mListener != null) {
                        mListener.finish();

                    }
                    return true;
                }
            case TYPE_CLOSE:
                if (mListener != null) {
                    mListener.finish();
                }
                return true;
            case TYPE_BROWSER:
                String url = params.get("url");
                if (mListener != null) {
                    mListener.turnOpenBrowser(url);
                }
                return true;
            default:
                if (mListener != null) {
                    mListener.turnOtherPage(params.get("event"), params);
                }
                return true;
        }
    }

    private Map<String, String> getParamsMap(String url) {
        Map<String, String> urlParamMap = new HashMap<>();
        if (url == null) {
            return urlParamMap;
        }
        String[] params = url.split("[?]");
        if (params.length <= 1) {
            return urlParamMap;
        }
        String[] keyValues = params[1].split("&");
        for (String keyValue : keyValues) {
            String[] map = keyValue.split("=");
            if (map.length != 2) {
                continue;
            }
            urlParamMap.put(map[0], map[1]);
        }
        return urlParamMap;
    }
}
